#include <iostream>
#include <string>
#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/base/CountDownLatch.h>
#include <unistd.h>

using std::cout;
using std::endl;
using std::string;

using namespace muduo;
using namespace muduo::net;
using namespace std::placeholders;

class DictClient
{
public:
    DictClient(const string &ip, short port, bool is_wait_connect = true)
        : _is_wait_connect(is_wait_connect), _connect_latch(1), _loop(_loopthread.startLoop()), _client(_loop, InetAddress(ip, port), "DictClient")
    {
        _client.setConnectionCallback(std::bind(&DictClient::onConnection, this, _1));
        _client.setMessageCallback(std::bind(&DictClient::onMessage, this, _1, _2, _3));
    }

    void connect()
    {
        _client.connect();

        if (_is_wait_connect)
            _connect_latch.wait();
    }

    void translate(const string &word)
    {
        if (_conn)
            _conn->send(word);
    }

    void shutdown()
    {
        _client.disconnect();
    }

private:
    void onMessage(const TcpConnectionPtr &ptr, Buffer *buf, Timestamp stamp)
    {
        string recvStr = buf->retrieveAllAsString();

        cout << "recv: " << recvStr << endl;
    }

    void onConnection(const TcpConnectionPtr &ptr)
    {
        if (ptr->connected())
        {
            _conn = ptr;
            if (_is_wait_connect)
                _connect_latch.countDown();

            cout << "CONNECT SUCCESS\n"
                 << endl;
        }
        else
        {
            _conn.reset();
            cout << "CONNECT SHUTDOWN\n"
                 << endl;
        }
    }

private:
    bool _is_wait_connect;
    muduo::CountDownLatch _connect_latch;
    muduo::net::EventLoopThread _loopthread;
    muduo::net::EventLoop *_loop;
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
};

int main(int args, char *argv[])
{
    DictClient client("127.0.0.1", 9090);
    client.connect();

    client.translate("你好");

    sleep(3);
    return 0;
}